﻿using Jint;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GameName1.Programming
{
    class Interpreter
    {
        Engine _engine;
        Thread _interpreterThread;
        string _code;

        //Singleton
        //private static Interpreter _instance;
        /*public static Interpreter Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new Interpreter();
                }
                return _instance;
            }
        }*/

        delegate void PrintDelegate(string str);
        delegate void SleepDelegate(int miliseconds);

        public Interpreter(RobotControl control)
        {
            _engine = new Engine();

            PrintDelegate printDelegate = new PrintDelegate(Notify);
            _engine.SetValue("print", printDelegate);
            _engine.SetValue("control", control);
            SleepDelegate sleepDelegate = new SleepDelegate(Sleep);
            _engine.SetValue("sleep", sleepDelegate);
            _interpreterThread = new Thread(new ThreadStart(InterpreterThreadFunction));
        }

        public void Run(string code)
        {
            _code = code;
            _interpreterThread.Start();

        }

        public void InterpreterThreadFunction()
        {
            try
            {
                _engine.Execute(_code);
            }
            catch (Exception ex)
            {
                // log errors
            }
        }


        void Notify(string name)
        {
            Debug.WriteLine("Javascript log: {0}", name);
            //_console.Text += "Javascript log: "+ name+"\r\n";
        }
        void Sleep(int miliseconds)
        {
            Thread.Sleep(miliseconds);
            //_console.Text += "Javascript log: "+ name+"\r\n";
        }
        


    }
}
